package com.datastructure.test.closestelement;

import java.util.ArrayList;

import java.util.stream.Collectors;

public class ClosestElement {

    public static void main(String[] args) {
        ClosestElement closestElement = new ClosestElement();
        ArrayList<Integer> nums = new ArrayList<>();
        for(int i =1;i<=5;i++){
            nums.add(i);
        }
        ArrayList<Integer> list = closestElement.closestElement(nums, 4, 0);
        System.out.println(list);
    }

    public ArrayList<Integer> closestElement (ArrayList<Integer> nums, int k, int x) {
        // write code here
        if(k> nums.size()){
            return nums;
        }
        ArrayList<Integer> result = new ArrayList<>();
        int index =0;
        for (int i = 0; i < nums.size(); i++) {
            Integer integer = nums.get(i);
            if(integer >x){
                index=i;
                result.add(integer);
                break;
            }
        }
        int left = index-1;
        int right = index+1;
        while (result.size()<k){
            if(right>=nums.size()){
                result.add(nums.get(left));
                left--;
                continue;
            }
            if(left<0){
                result.add(nums.get(right));
                right++;
                continue;
            }
            if(Math.abs(nums.get(left)-x)>Math.abs(nums.get(right)-x)){
                result.add(nums.get(right));
                right++;
            } else {
                result.add(nums.get(left));
                left--;
            }
        }
        ArrayList<Integer> collect = (ArrayList<Integer>)result.stream().sorted().collect(Collectors.toList());
        return collect;
    }
}
